﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;

using System.Web;

using Castle.Services.Transaction;
using Castle.Facilities.IBatisNetIntegration;

using Meqs.Entity;
using Meqs.Logic.Interface;
using Sunrise.Spell;

namespace Meqs.Logic.Implement
{
    public class TeacherInfoLogic : CommonLogic<TeacherInfo, int>, ITeacherInfoLogic
    {

        #region Implementation of ICommonLogic<TeacherInfo, int>

        /// <sammury>
        /// 创建对象
        /// </sammury>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Create(TeacherInfo entity)
        {
            return CreateObject(entity);
        }

        /// <sammury>
        /// 更新对象
        /// </sammury>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int Update(TeacherInfo entity)
        {
            return UpdateObject(entity);
        }

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public int Delete(int entityId)
        {
            return DeleteObject(entityId);
        }

        /// <summary>
        /// 删除所有对象
        /// </summary>
        /// <returns></returns>
        public int DeleteAll()
        {
            return DeleteAllObject();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public TeacherInfo FindById(int entityId)
        {
            return FindObjectById(entityId);
        }

        /// <summary>
        /// 检索对象数量
        /// </summary>
        /// <returns></returns>
        public int FindCount()
        {
            return FindObjectByCount();
        }

        /// <sammury>
        /// 检索对象
        /// </sammury>
        public IList<TeacherInfo> FindAll()
        {
            return FindAllObject();
        }

        /// <summary>
        /// 检索对象数量
        /// </summary>
        /// <returns></returns>
        public int FindCount(Hashtable table)
        {
            return FindObjectByCount(table);
        }

        /// <sammury>
        /// 检索对象
        /// </sammury>
        public IList<TeacherInfo> FindAll(Hashtable table)
        {
            return FindObject(table);
        }

        #endregion

        /// <summary>
        /// 根据拼音查询教师
        /// </summary>
        /// <param name="pinyin"></param>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public IList<TeacherInfo> GetTeacherByPinyin(string pinyin, string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("TeachNamePinYin", pinyin);
            ht.Add("SchoolMark", schoolMark);
            ht.Add("IsAdmin", false);
            return FindCustomer<TeacherInfo>("TeacherInfo.GetTeacherByPinyin", ht);
        }

        public IList<TeacherInfo> FindClassTeachers(Hashtable ht)
        {
            return FindCustomer<TeacherInfo>("TeacherInfo.FindClassTeachers", ht);
        }
        /// <summary>
        /// 根据拼音查询教师
        /// </summary>
        /// <param name="pinyin"></param>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public  IList<TeacherInfo> GetTeacherByPinyinWithoutEffect(string pinyin, string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("TeachNamePinYin", pinyin);
            ht.Add("SchoolMark", schoolMark);
            ht.Add("IsAdmin", false);
            return FindCustomer<TeacherInfo>("TeacherInfo.GetTeacherByPinyinWithoutEffect", ht);
        }

        /// <summary>
        /// 根据拼音排序得到所有教师信息
        /// </summary>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public IList<TeacherInfo> GetAllTeacherOrderByPinyin(string schoolMark)
        {
            Hashtable ht = new Hashtable();
            ht.Add("SchoolMark", schoolMark);
            ht.Add("IsAdmin", false);
            ht.Add("IsEffect", 1);

            List<TeacherInfo> list = (List<TeacherInfo>)FindCustomer<TeacherInfo>("TeacherInfo.FindByPinyin", ht);
            foreach (TeacherInfo teacherInfo in list)
            {
                if (teacherInfo.TeachNamePinYin != "")
                    teacherInfo.TeachNamePinYin = teacherInfo.TeachNamePinYin.Substring(0, 1);
            }

            return list;
        }

        /// <summary>
        /// 删除教工所有信息
        /// </summary>
        /// <returns></returns>
        [Transaction(TransactionMode.Requires)]
        public int DeleteTeacherInfo(List<int> listUserId)
        {
            foreach (int userId in listUserId)
            {
                TeacherInfo teacherInfo = FindById(userId);
                if (teacherInfo != null)
                {
                    teacherInfo.IsEffect = false;
                    Update(teacherInfo);
                }
            }
            return 1;
        }

        /// <summary>
        /// 重置用户密码，可批量
        /// </summary>
        /// <param name="listUserId"></param>
        /// <returns></returns>
        public int ResetPassword(List<int> listUserId)
        {
            foreach (int userId in listUserId)
            {
                Hashtable ht = new Hashtable();
                ht.Add("RID", userId);
                ht.Add("IsEffect", true);

                UpdateCustomer("TeacherInfo.ResetPassword", ht);
            }
            return 1;
        }

        /// <summary>
        /// 将List里面的教师的密码重置为strPwd
        /// </summary>
        /// <param name="strPwd"></param>
        /// <param name="listUserId"></param>
        /// <returns></returns>
        public int ResetPassword(string strPwd, List<int> listUserId)
        {
            foreach (int userId in listUserId)
            {
                Hashtable ht = new Hashtable();
                ht.Add("RID", userId);
                ht.Add("IsEffect", true);
                ht.Add("Passwd", strPwd);

                UpdateCustomer("TeacherInfo.CustomResetPassword", ht);
            }
            return 1;
        }

        /// <summary>
        /// 要据条件获取教师信息
        /// </summary>
        /// <param name="ht"></param>
        /// <returns></returns>
        public IList<CustomTeacherInfo> FindTeacherByCause(Hashtable ht)
        {
            List<TeacherInfo> Teachers = (List<TeacherInfo>)FindCustomer<TeacherInfo>("TeacherInfo.FindTeachByCause", ht);

            List<CustomTeacherInfo> results = new List<CustomTeacherInfo>();

            foreach (TeacherInfo teachInfo in Teachers)
            {
                Hashtable hash = new Hashtable();
                ht.Add("TeachID",teachInfo.RID);

                List<CustomTeacherInfo> teachCause = (List<CustomTeacherInfo>)FindCustomer<CustomTeacherInfo>("TeacherInfo.FindTeacherByCause", ht);

                CustomTeacherInfo tt = new CustomTeacherInfo();
                string strGradeCls = "";
                for(int i = 0; i<teachCause.Count; i++)
                {
                    if (strGradeCls != "")
                        strGradeCls = strGradeCls + ",";

                    strGradeCls = strGradeCls + teachCause[i].ClsSubName;
                }
                if (strGradeCls == "")
                    strGradeCls = "无";

                tt.RID = teachInfo.RID;
                tt.TeachCode = teachInfo.TeachCode;
                tt.TeachName = teachInfo.TeachName;
                tt.ClsSubName = strGradeCls;

                results.Add(tt);

                ht.Remove("TeachID");
            }
            return results;
        }

        /// <summary>
        /// 根据教师工号更新教师信息
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public int UpdateByTeacherCode(TeacherInfo teacherInfo)
        {
            return UpdateCustomer("TeacherInfo.UpdateByTeacherCode", teacherInfo);
        }

        /// <summary>
        /// 导入教师数据
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        [Transaction(TransactionMode.Requires)]
        public int ImportTeacherInfo(string schoolMark, DataTable dt, int opType)
        {
            //0列，教师工号
            //1列，教师姓名
            string time = "1800-1-1 00:00:00";
            DateTime minTime = Convert.ToDateTime(time);

            TeacherInfo teacherInfo = new TeacherInfo();

            int iUpdateRes = 0;
            int iInsertRes = 0;
            
            foreach (DataRow row in dt.Rows)
            {
                teacherInfo.SchoolMark = schoolMark;
                teacherInfo.TeachCode = row[0].ToString();
                teacherInfo.TeachName = row[1].ToString();
                teacherInfo.IsEffect = true;

                if (teacherInfo.TeachCode == "" || teacherInfo.TeachName == "")
                    continue;

                try   { teacherInfo.Sexy = Convert.ToInt16(row[2]); }
                catch { teacherInfo.Sexy = 0; }

                try 
                { 
                    teacherInfo.Birthday = DateTime.Parse(row[3].ToString());
                    if (DateTime.Compare(minTime, teacherInfo.Birthday) >= 0)
                        teacherInfo.Birthday = DateTime.MaxValue;
                }
                catch { teacherInfo.Birthday = DateTime.MaxValue; }

                try 
                { 
                    teacherInfo.InSchoolDate = DateTime.Parse(row[4].ToString());
                    if (DateTime.Compare(minTime, teacherInfo.InSchoolDate) >= 0)
                        teacherInfo.InSchoolDate = DateTime.MaxValue;
                }
                catch { teacherInfo.InSchoolDate = DateTime.MaxValue; }

                try
                {
                    teacherInfo.TeachNamePinYin = Sunrise.Spell.Spell.MakeSpellCode(teacherInfo.TeachName, SpellOptions.EnableUnicodeLetter);
                    if (teacherInfo.TeachNamePinYin == "")
                        teacherInfo.TeachNamePinYin = " ";
                }
                catch{ teacherInfo.TeachNamePinYin = " "; }
                
                ////取得拼音的首位
                //if (teacherInfo.TeachNamePinYin != "")
                //    teacherInfo.TeachNamePinYin = teacherInfo.TeachNamePinYin.Substring(0, 1);

                if (opType == 1)                        //覆盖已经存在的教师数据
                    iUpdateRes = UpdateByTeacherCode(teacherInfo);

                if (opType == 0)                        //不覆盖已经存在的教师数据
                    iUpdateRes = 0;

                //如果更新失败则直接添加教师数据
                if (iUpdateRes == 0)
                {
                    teacherInfo.TeachCode = row[0].ToString();
                    teacherInfo.TeachName = row[1].ToString();
                    teacherInfo.Passwd = "123456";
                    teacherInfo.IsEffect = true;
                    teacherInfo.IsAdmin = 0;
                    teacherInfo.SchoolMark = schoolMark;
                    teacherInfo.TeachCode.Trim();
                    teacherInfo.TeachName.Trim();

                    try { teacherInfo.Sexy = Convert.ToInt16(row[2]); }
                    catch { teacherInfo.Sexy = 0; }

                    try
                    {
                        teacherInfo.Birthday = DateTime.Parse(row[3].ToString());
                        if (DateTime.Compare(minTime, teacherInfo.Birthday) >= 0)
                            teacherInfo.Birthday = DateTime.MaxValue;
                    }
                    catch { teacherInfo.Birthday = DateTime.MaxValue; }

                    try
                    {
                        teacherInfo.InSchoolDate = DateTime.Parse(row[4].ToString());
                        if (DateTime.Compare(minTime, teacherInfo.InSchoolDate) >= 0)
                            teacherInfo.InSchoolDate = DateTime.MaxValue;
                    }
                    catch { teacherInfo.InSchoolDate = DateTime.MaxValue; }

                    try
                    {
                        teacherInfo.TeachNamePinYin = Sunrise.Spell.Spell.MakeSpellCode(teacherInfo.TeachName, SpellOptions.EnableUnicodeLetter);
                        if (teacherInfo.TeachNamePinYin == "")
                            teacherInfo.TeachNamePinYin = " ";
                    }
                    catch
                    { teacherInfo.TeachNamePinYin = " "; }

                    ////取得拼音的首位
                    //if (teacherInfo.TeachNamePinYin != "")
                    //    teacherInfo.TeachNamePinYin = teacherInfo.TeachNamePinYin.Substring(0, 1);

                    //判断数据是否存在，在全部的已经作废的数据和未作废的数据中进行查询
                    Hashtable hs = new Hashtable();
                    hs.Add("TeachCode", teacherInfo.TeachCode);
                    //hs.Add("IsEffect", teacherInfo.IsEffect);
                    hs.Add("SchoolMark", teacherInfo.SchoolMark);

                    List<TeacherInfo> list = (List<TeacherInfo>)FindAll(hs);
                    if (list.Count == 0)        //未查找到相同数据,则添加，找到相同数据则忽略该数据
                    {
                        iInsertRes = CreateObject(teacherInfo);
                        if (iInsertRes <= 0)
                            return 0;
                    }

                //    if (opType == 1)                                //直接添加教师数据
                //        iInsertRes = CreateObject(teacherInfo);

                //    if (opType == 0)                                //先判断该数据是否存在，再添加教师数据
                //    {
                //        Hashtable hs = new Hashtable();
                //        hs.Add("TeachCode", teacherInfo.TeachCode);
                //        hs.Add("IsEffect", teacherInfo.IsEffect);
                //        hs.Add("SchoolMark", teacherInfo.SchoolMark);

                //        List<TeacherInfo> list = (List<TeacherInfo>)FindAll(hs);
                //        if (list.Count == 0)                        //未查找到相同数据 
                //            iInsertRes = CreateObject(teacherInfo);
                //        else
                //            iInsertRes = 1;                         //不需要添加数据时直接返回正确的插入结果
                //    }

                //    if (iInsertRes <= 0) 
                //        return 0;
                }
            }

            return 1;
        }

        /// <summary>
        /// 根据工号查教师
        /// </summary>
        /// <param name="teacherCode"></param>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public TeacherInfo FindTeachByCode(string teacherCode, string schoolMark)
        {
            try
            {
                Hashtable ht = new Hashtable();
                ht.Add("TeachCode", teacherCode);
                ht.Add("SchoolMark", schoolMark);
                return FindCustomerByID<TeacherInfo>("TeacherInfo.FindTeachByCode", ht);
            }
            catch (Exception)
            {
                return null;
            }
        }


        public int CheckLogin(string schoolCode, string teachCode, string pass)
        {
            Hashtable ht = new Hashtable();
            ht.Add("SchoolCode", schoolCode);//学校编号
            ht.Add("IsEffect", 1);//是否有效
            IList<SchoolInfo> chlList = this.ExecuteQueryForList<SchoolInfo>("SchoolInfo.Find", ht);
            //判断学校编号的合法性
            if (chlList.Count <= 0)//学校编号错误
            {
                return 0;
            }
            ht.Clear();
            string schoolMark = chlList[0].SchoolMark;
            ht.Add("SchoolMark", schoolMark);
            ht.Add("TeachCode", teachCode);
            //判断用户合法性
            IList<TeacherInfo> list = this.ExecuteQueryForList<TeacherInfo>("TeacherInfo.FindByCodeAndShoolMark", ht);
            if (list.Count <= 0)//用户名错误
            {
                return 1;
            }
            if (list[0].Passwd != pass)//密码错误
            {
                return 2;
            }
            Perm perm = new Perm();
            if (list[0].IsAdmin==1)
            {
                perm.UserType = 3;
            }
            else
            {
                perm.UserType = 4;
                ht.Clear();
                ht.Add("TeacherID", list[0].RID);
                IList<SchPrem> premlist = this.ExecuteQueryForList<SchPrem>("SchPrem.Find", ht);
               
                foreach (SchPrem schPrem in premlist)
                {

                    ht = new Hashtable();
                    ht.Add("HeaderID", list[0].RID);
                    ht.Add("SchoolMark", schoolMark);
                    IList<ClsInfo> idList = this.ExecuteQueryForList<ClsInfo>("ClsInfo.Find", ht);
                    foreach (ClsInfo info in idList)
                    {
                        if(!perm.OwnClassIDList.Contains(info.RID))
                            perm.OwnClassIDList.Add(info.RID);
                    }

                    ht = new Hashtable();
                    ht.Add("TeachID", list[0].RID);
                    ht.Add("SchoolMark", schoolMark);
                    IList<TeachClsCause> clsidList = this.ExecuteQueryForList<TeachClsCause>("TeachClsCause.Find", ht);
                    foreach (TeachClsCause info in clsidList)
                    {
                        if (!perm.OwnClassIDList.Contains(info.ClsID))
                            perm.OwnClassIDList.Add(info.ClsID);
                    }

                    switch (schPrem.PNo)
                    {
                        case 1:
                            perm.School_Tech_EvalSet = true;
                            break;
                        case 2:
                            perm.School_Tech_StuEval = true;
                            break;
                        case 3:
                            perm.School_Tech_Report = true;
                            break;
                        case 4:
                            perm.School_Tech_TableSet = true;
                            break;
                        case 11:

                            break;
                        case 12:

                            break;
                        case 21:
                            perm.School_Score_EduExam = true;
                            break;
                        case 22:
                            perm.School_Score_SchoolExam = true;
                            break;
                        case 23:
                            perm.School_Score_Report = true;
                            break;
                        case 41:
                            perm.School_Morality_Role = true;
                            break;
                        case 42:
                            perm.School_Morality_Report = true;
                            break;
                        case 51:
                            perm.School_Credit_Role = true;
                            break;
                        case 52:
                            perm.School_Credit_Report = true;
                            break;
                    }
                }
            }//用户类型:校级普通用户
            perm.SchoolMark = schoolMark;//学校标识
            perm.SchoolName = chlList[0].SchoolName;
            perm.DataUserName = "S" + chlList[0].RID;//学校数据库用户名
            perm.UserName = teachCode;//学号
            perm.UName = list[0].TeachName;//学生姓名
            perm.UID = list[0].RID;
            perm.SchoolAreaId=chlList[0].AreaID;
            ht.Clear();
            ht.Add("RID",chlList[0].AreaID);
            SchoolArea schoolArea = this.ExecuteQueryForObject<SchoolArea>("SchoolArea.FindById", ht);
            if (schoolArea != null)
            {
                perm.SchoolAreaName = schoolArea.SchoolAreaName;
            }

            HttpCookie shlMark = new HttpCookie("SchoolMark", schoolCode);
            shlMark.Expires = DateTime.Now.AddMonths(12);
            HttpContext.Current.Response.AppendCookie(shlMark);
            HttpCookie loginWayCookie = new HttpCookie("LoginWay", "2");
            loginWayCookie.Expires = DateTime.Now.AddMonths(12);
            HttpContext.Current.Response.AppendCookie(loginWayCookie);
            HttpContext.Current.Session["UserInfo"] = perm;

            ht = new Hashtable();
            ht.Add("TeacherID", list[0].RID);//教师ID
            ht.Add("SchoolYear", chlList[0].SchoolYear);//学年
            ht.Add("Term", chlList[0].SchoolTerm);//学期
            ht.Add("SchoolMark", schoolMark);//学校编号
            IList<TeacherRoles> teachRoles = this.ExecuteQueryForList<TeacherRoles>("TeacherRoles.Find", ht);
            HttpContext.Current.Session["UserRoles"] = teachRoles;

 
            ht = new Hashtable();
            ht.Add("TeacherID", list[0].RID);
            teachRoles = this.ExecuteQueryForList<TeacherRoles>("TeacherRoles.Find", ht);
            HttpContext.Current.Session["UserHistoryPositionRoles"] = teachRoles;

            return 3;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="teacherID"></param>
        /// <param name="pinyin"></param>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public IList<TeacherInfo> GetTeacherByPinyin(int teacherID, string pinyin, string schoolMark)
        {
            try
            {
                Hashtable ht = new Hashtable();
                ht.Add("TeachID", teacherID);
                ht.Add("SchoolMark", schoolMark);
                string causeIDList = FindCustomerByID<string>("EvalSettings.GetResearchIDListByTeacher", ht);

                if (string.IsNullOrEmpty(causeIDList)) return new List<TeacherInfo>();
                causeIDList = causeIDList.TrimEnd(',');
                ht.Clear();
                ht.Add("CauseIDList", causeIDList);
                ht.Add("TeachNamePinYin", pinyin);
                ht.Add("SchoolMark", schoolMark);
                IList<TeacherInfo> list = FindCustomer<TeacherInfo>("TeacherInfo.GetTeacherByPinyin", ht);
                return list;
            }
            catch (Exception)
            {
                return new List<TeacherInfo>();
            }
        }

        /// <summary>
        ///  获取指定年级下所有班级的班主任信息
        /// </summary>
        /// <param name="grade"></param>
        /// <param name="schoolMark"></param>
        /// <returns></returns>
        public IList<HeaderInfo> FindHeaderByGrade(int grade, string schoolMark)
        {
            Hashtable table = new Hashtable();
            if(grade > 0)
                table.Add("grade", grade);
            table.Add("SchoolMark", schoolMark);

            return FindCustomer<HeaderInfo>("TeacherInfo.FindHeaderByGrade", table);
        }
    }
}